'use strict';
/**
 * 黄总--model仓库类
 *2017.5.13
 */

export default class extends think.Model {

	/*
	**构想关于事务的回滚操作
	**事务暂时先不在model层处理，因为model层的操作在逻辑层是被当做原子对待
	**事务放在逻辑层吧
	*/

	/*
	**改变商品的库存
	**输入[{
		goodsid:商品id,
		nums:数量-正加负减,
		orderid:订单id,
		ordertype:订单类型,
		deparementid:店家id,
		addtime:变动时间
	}]
	**返回执行结果
	*/
	async changegoodsnums(data,model){
		let dl = data.length;
		if(0==dl){
			return false;
		}
		let goodsdata = [];
		for (let i = dl - 1; i >= 0; i--) {
			goodsdata.push({
				id:data[i].goodsid,
				nums:'`nums`+'+data[i].nums,
			});
		};
		let resgoods,resgoodslog;
		if(model){
			resgoods = await this.model('or_shop_goods').db(model.db()).updateMany(goodsdata);
			resgoodslog = await this.model('or_shop_goodslog').db(model.db()).addMany(data);
		}else{
			resgoods = await this.model('or_shop_goods').updateMany(goodsdata);
			resgoodslog = await this.model('or_shop_goodslog').addMany(data);
		}	
		return resgoods&&resgoodslog?true:false;
	}

	/*
	*商品库存回滚
	*用于删除订单时
	*orderid,ordertype
	*/
	async backgoodsnums(orderid,ordertype){
		let resgoods,reslog;
		let olist = await this.model('or_shop_orderinfo').where({orderid:orderid,type:1}).select();
		resgoods = true;
		if(!think.isEmpty(olist)){
			for (var i = olist.length - 1; i >= 0; i--) {
				let res = await this.model('or_shop_goods').decrement('nums',olist[i].num);
				if(!res){
					resgoods = false;
				}
			};
		}

		//删除日志
		reslog = await this.model('or_shop_goodslog').where({orderid:orderid,ordertype:ordertype}).delete();
		return resgoods&&reslog?true:false;
	}


}